/*
 * 
 * 微慕小程序开源版
 * author: jianbo
 * organization: 微慕  www.minapper.com
 * github:    https://github.com/iamxjb/winxin-app-watch-life.net
 * 技术支持微信号：iamxjb
 * 开源协议：MIT
 * 
 *  *Copyright (c) 2017 https://www.minapper.com All rights reserved.
 */

var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var wxApi = require('../../utils/wxApi.js')
const Adapter = require('../../utils/adapter.js')
var wxRequest = require('../../utils/wxRequest.js')

import config from '../../utils/config.js'
var pageCount = config.getPageCount;
var webSiteName = config.getWebsiteName;
var domain = config.getDomain

Page({
  data: {
    title: '文章列表',
    postsList: {},
    pagesList: {},
    category: {},
    tag: {},
    postsShowSwiperList: {},
    isLastPage: false,
    page: 1,
    search: '',
    showerror: false,
    type: null,
    showallDisplay: "block",
    displaySwiper: "block",
    floatDisplay: "none",
    searchKey: "",
    webSiteName: webSiteName,
    domain: domain,
    listAdsuccess: true,
    isLoading: false
  },
  formSubmit: function (e) {
    var url = '../list/list'
    if (e.detail.value.input != '') {
      url = url + '?search=' + e.detail.value.input;
    }
    wx.navigateTo({
      url: url
    })
  },
  onShareAppMessage: function () {
    var title = "分享“" + webSiteName + "”";
    var path = ""
    if (this.data.category.id && this.data.category.id != 0) {
      title += "的专题：" + this.data.category.name;
      path = 'pages/list/list?categoryID=' + this.data.category.id;

    } if (this.data.tag.id && this.data.tag.id != 0) {
      title += "的标签：" + this.data.tag.name;
      path = 'pages/list/list?tagID=' + this.data.tag.id;
    } else {
      title += "的搜索内容：" + this.data.searchKey;
      path = 'pages/list/list?search=' + this.data.searchKey;
    }


    return {
      title: title,
      path: path,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  onShareTimeline: function () {

    var path = ""
    var query = {};
    var title = "";
    if (this.data.type == 'category') {
      title += this.data.category.name + "-" + this.data.category.description;
      query = {
        'categoryID': this.data.category.id
      };
    }
    else if (this.data.type == 'tag') {
      title += this.data.tag.name + "-" + this.data.tag.description;
      query = {
        'tagID': this.data.tag.id
      };
    } else {
      title += webSiteName + "的搜索内容：" + this.data.searchKey;
      query = {
        search: this.data.searchKey
      };
    }

    return {
      title: title,
      path: 'pages/list/list',
      query: query,
      imageUrl: this.data.categoriy.category_thumbnail_image
    }
  },
  onReachBottom: function () {
    var self = this;
    if (!self.data.isLastPage) {
      self.setData({
        page: self.data.page + 1
      });
      console.log('当前页' + self.data.page);
      this.fetchPostsData(self.data);
    } else {
      console.log('最后一页');
    }

  },
  reload: function (e) {
    var self = this;
    if (self.data.category.id && self.data.category.id != 0) {

      self.setData({
        type: 'category',
        showallDisplay: "none",
        showerror: false,

      });
      self.fetchCategoriesData(self.data.category.id);
    }
    if (self.data.search && self.data.search != '') {
      self.setData({
        type: 'search',
        showallDisplay: "none",
        showerror: false,
        searchKey: self.data.search
      })
    }
    self.fetchPostsData(self.data);
  },
  //加载分页
  loadMore: function (e) {
    var self = this;
    if (!self.data.isLastPage) {
      self.setData({
        page: self.data.page + 1
      });
      console.log('当前页' + self.data.page);
      this.fetchPostsData(self.data);
    } else {
      wx.showToast({
        title: '没有更多内容',
        mask: false,
        duration: 1000
      });
    }
  },
  onLoad: function (options) {
    var self = this;
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline'],
      success: function (e) {
        //console.log(e);
      }
    })
    // 设置插屏广告
    Adapter.setInterstitialAd("enable_list_interstitial_ad");
    if (options.categoryID && options.categoryID != 0) {
      self.setData({
        'category.id': options.categoryID,
        type: 'category'
      });
      self.fetchCategoriesData(options.categoryID);
    }
    if (options.search && options.search != '') {
      wx.setNavigationBarTitle({
        title: "搜索"
      });
      self.setData({
        search: options.search,
        type: 'search',
        searchKey: options.search
      })
    }
    if (options.tagID) {
      self.setData({
        type: 'tag',
        'tag.id': options.tagID
      });
      self.fetchTagData(options.tagID);
    }
    this.fetchPostsData(self.data);
  },
  //获取文章列表数据
  fetchPostsData: function (data) {
    var self = this;
    if (!data) data = {};
    if (!data.page) data.page = 1;
    if (data.page === 1) {
      self.setData({
        postsList: []
      });
    };
    self.setData({
      isLoading: true
    })
    var getPostsRequest = wxRequest.getRequest(Api.getPosts({
      page: self.data.page,
      categories: self.data.category.id,
      tags: self.data.tag.id,
      search: self.data.seach
    }));
    getPostsRequest.then(response => {
      if (response.statusCode === 200) {
        if (response.data.length < pageCount) {
          self.setData({
            isLastPage: true,
            isLoading: false
          });
        };
        self.setData({
          floatDisplay: "block",
          showallDisplay: "block",
          postsList: self.data.postsList.concat(response.data.map(function (item) {
            var strdate = item.date
            item.date = util.cutstr(strdate, 10, 1);
            return item;
          })),

        });

      } else {
        if (response.data.code == "rest_post_invalid_page_number") {
          self.setData({
            isLastPage: true,
            isLoading: false
          });

        } else {
          wx.showToast({
            title: response.data.message,
            duration: 1500
          })
        }
      }
    }).catch(function () {
      if (data.page == 1) {
        self.setData({
          showerror: true,
          floatDisplay: "none"
        });
      } else {
        wx.showModal({
          title: '加载失败',
          content: '加载数据失败,请重试.',
          showCancel: false,
        });
        self.setData({
          page: data.page - 1
        });
      }
    }).finally(function () {
      self.setData({
        isLoading: false
      })

    })
  },



  // 跳转至查看文章详情
  redictDetail: function (e) {
    // console.log('查看文章');
    var id = e.currentTarget.id,
      url = '../detail/detail?id=' + id;
    wx.navigateTo({
      url: url
    })
  },
  fetchTagData(id) {
    var self = this;
    var getTagRequest = wxRequest.getRequest(Api.getTagByID(id));
    getTagRequest.then(response => {
      self.setData({
        tag: response.data,
      });

      wx.setNavigationBarTitle({
        title: response.data.name,
        success: function (res) {
          // success
        }
      });
    })
  },
  //获取分类列表
  fetchCategoriesData: function (id) {
    var self = this;
    // self.setData({
    //   category: {}
    // });

    var getCategoryRequest = wxRequest.getRequest(Api.getCategoryByID(id));
    getCategoryRequest.then(response => {
      self.setData({
        category: response.data,
      });

      wx.setNavigationBarTitle({
        title: response.data.name,
        success: function (res) {
          // success
        }
      });
    })
  },
  adbinderror: function (e) {
    var self = this;
    console.log(e.detail.errCode);
    console.log(e.detail.errMsg);
    if (e.detail.errCode) {
      self.setData({
        listAdsuccess: false
      })
    }

  }


})